package com.beamfield.controller.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.beamfield.common.AESSecurityUtil;
import com.beamfield.common.LogInfo;
import com.beamfield.common.TokenManage;
import com.beamfield.modelVo.Qrcode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

/**
 * @author Zephyr
 * @Description:
 * @Date 2018/10/10
 */
public class MbBaseController extends BaseController {

    private static final String TOKEN = "token";

    private static final String BODY = "body";

    private static final String SYSTEM = "beamfiled";

    @Override
    protected Long getUserId(HttpServletRequest req) {
        LogInfo logInfo = this.getLogInfo(req);
        if(logInfo != null){
            return logInfo.getUserId();
        }
        return 0L;
    }

    @Override
    protected Long getBeamId(HttpServletRequest req) {
        LogInfo logInfo = this.getLogInfo(req);
        if(logInfo != null){
            return logInfo.getBeamId();
        }
        return 0L;
    }

    protected LogInfo getLogInfo(HttpServletRequest request){
        String token = this.getToken(request);
        return TokenManage.get(token);
    }

    protected String getToken(HttpServletRequest request){
        return (String)request.getAttribute(TOKEN);
    }

    protected JSONObject getBody(HttpServletRequest request){
        return (JSONObject) request.getAttribute(BODY);
    }

    protected Qrcode getQrcode(String qrCodeJson){
        if(StringUtils.isEmpty(qrCodeJson)){
            return null;
        }
        Qrcode qrcode = null;
        try {
            List<Qrcode> qrcodeList = JSON.parseArray(qrCodeJson, Qrcode.class);
            if(CollectionUtils.isEmpty(qrcodeList)){
                return null;
            }
            qrcode = qrcodeList.get(0);
            if(qrcode != null){
                String system = qrcode.getSystem();
                if(!Objects.equals(system, SYSTEM)){
                    return null;
                }
                qrcode.setBeam(AESSecurityUtil.decrypt(qrcode.getBeam(), AESSecurityUtil.INIT_KEY));
                qrcode.setData(AESSecurityUtil.decrypt(qrcode.getData(), AESSecurityUtil.INIT_KEY));
                qrcode.setType(AESSecurityUtil.decrypt(qrcode.getType(), AESSecurityUtil.INIT_KEY));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return qrcode;
    }
}
